package com.meichis.mcsappframework.camera;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Environment;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.meichis.mcsappframework.R;
import com.meichis.mcsappframework.adapter.abslistview.CommonAdapter;
import com.meichis.mcsappframework.adapter.abslistview.ViewHolder;
import com.meichis.mcsappframework.entity.TakePhotoParam;
import com.meichis.mcsappframework.utils.BitmapUtil;
import com.meichis.mcsappframework.utils.DateUtil;
import com.meichis.mcsappframework.utils.MessageTools;
import com.nostra13.universalimageloader.core.DisplayImageOptions;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/7/8.
 */
public class CameraActivity extends Activity implements OnClickListener {

    private Camera camera;
    private int camera_direction = Camera.CameraInfo.CAMERA_FACING_FRONT; //摄像头方向
    private int camera_id = 0;//当前启动摄像头的id
    private RelativeLayout rl_takephoto, rl_prephoto; //拍照界面和预览界面
    private SurfaceView sv_camera;
    private ImageView iv_preview, iv_shutter, iv_switch;
    private TextView tv_back, tv_light;
    private Gallery gy_pic;
    private ArrayList<String> picPaths = new ArrayList<>();//照片路径
    private Bitmap cameraBitmap;
    private MyOrientationEventListener myOrientation;//方向监听器
    private TakePhotoParam photoParam;
    private int heightPixels, widthPixels;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        setParams();
        findViews();
        setViews();
        heightPixels = CameraUtils.GetMetrics(this).heightPixels;
        widthPixels = CameraUtils.GetMetrics(this).widthPixels;
    }

    private void setParams() {
        photoParam = (TakePhotoParam) getIntent().getSerializableExtra("TakePhotoParam");
        if (photoParam == null) {
            //没有设置，缺省值
            photoParam = new TakePhotoParam();
        }
        if (photoParam.getMaxMember() == 0) {
            photoParam.setMaxMember(100);//默认一次最多拍100张
        }
        if (photoParam.getPicHight() == 0) {
            photoParam.setPicHight(1920);
        }
        if (photoParam.getPicQuality() == 0) {
            photoParam.setPicQuality(80);
        }
        if (photoParam.getPicPath() == null || photoParam.getPicPath().trim().equals("")) {
            photoParam.setPicPath(getExternalFilesDir(Environment.DIRECTORY_PICTURES) + "/" + getResources().getString(R.string.app_code) + "/TakePhoto/");
        }
        if (photoParam.getPicPre() == null) {
            photoParam.setPicPre("");
        }
    }

    private void findViews() {
        rl_takephoto = (RelativeLayout) findViewById(R.id.rl_takephoto);
        rl_prephoto = (RelativeLayout) findViewById(R.id.rl_prephoto);
        sv_camera = (SurfaceView) findViewById(R.id.sv_camera);
        iv_preview = (ImageView) findViewById(R.id.iv_preview);
        iv_shutter = (ImageView) findViewById(R.id.iv_shutter);
        gy_pic = (Gallery) findViewById(R.id.gy_pic);
        tv_back = (TextView) findViewById(R.id.include).findViewById(R.id.titlebar_left_text);
        tv_light = (TextView) findViewById(R.id.include).findViewById(R.id.titlebar_title_text);
        iv_switch = (ImageView) findViewById(R.id.include).findViewById(R.id.titlebar_right_pic);

    }

    private void setViews() {
        tv_back.setText(R.string.titlebar_confirm);
        tv_light.setText(R.string.turn_on_lights);
        iv_switch.setImageResource(R.mipmap.ic_switch_camera);

        tv_back.setOnClickListener(this);
        tv_light.setOnClickListener(this);
        iv_shutter.setOnClickListener(this);
        iv_switch.setOnClickListener(this);
        findViewById(R.id.iv_cancel).setOnClickListener(this);
        findViewById(R.id.iv_save).setOnClickListener(this);
        //先显示拍照界面，隐藏预览界面
        rl_takephoto.setVisibility(View.VISIBLE);
        rl_prephoto.setVisibility(View.GONE);

        sv_camera.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        sv_camera.getHolder().setKeepScreenOn(true);// 屏幕常亮
        sv_camera.getHolder().addCallback(surfaceCallback);//为SurfaceView的句柄添加一个回调函数
        gy_pic.setAdapter(picAdapter);
    }

    /**
     * 转换摄像头
     */
    public void switchCamera() {

        if (camera_direction == Camera.CameraInfo.CAMERA_FACING_BACK) {
            camera_direction = Camera.CameraInfo.CAMERA_FACING_FRONT;
        } else {
            camera_direction = Camera.CameraInfo.CAMERA_FACING_BACK;
        }
        int mNumberOfCameras = Camera.getNumberOfCameras();
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        for (int i = 0; i < mNumberOfCameras; i++) {
            Camera.getCameraInfo(i, cameraInfo);
            if (cameraInfo.facing == camera_direction) {
                camera_id = i;
            }
        }
        try {
            cameraDestory();
            camera = Camera.open(camera_id);
            camera.setDisplayOrientation(90);//因为摄像头默认是横屏显示，调正
            setCameraAndDisplay();
            camera.setPreviewDisplay(sv_camera.getHolder());
            camera.startPreview();
        } catch (Exception e) {
            e.printStackTrace();
            MessageTools.showLongToast("打开相机失败！请检查相机设备或相机权限");
            onBackPressed();
            return;
        }
    }

    /**
     * 设置摄像头显示以及照片
     */
    public void setCameraAndDisplay() {
        if (camera != null) {
            Camera.Parameters parameters = camera.getParameters();
            // 设置图片格式
            parameters.setPictureFormat(PixelFormat.JPEG);
            // 设置照片质量
            parameters.setJpegQuality(100);
            //设置每秒显示4帧
//            parameters.setPreviewFrameRate(4);
            //获取摄像头支持的PictureSize列表
            List<Camera.Size> pictureSizeList = parameters.getSupportedPictureSizes();
            //从列表中选取接近设置的分辨率
            Camera.Size picSize = CameraUtils.getProperSize(pictureSizeList, photoParam.getPicHight());
            parameters.setPictureSize(picSize.width, picSize.height); // 设置保存的图片尺寸

            //先判断是否支持，否则会报错
            if (parameters.getSupportedFocusModes().contains(Camera.Parameters.FOCUS_MODE_AUTO))
                parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
            camera.cancelAutoFocus();
            camera.setParameters(parameters);
            try {
                parameters.setPreviewSize(heightPixels, widthPixels);
                sv_camera.setLayoutParams(new RelativeLayout.LayoutParams(widthPixels, heightPixels));
            } catch (Exception e) {
                e.printStackTrace();
                //获取摄像头支持的PreviewSize列表
                List<Camera.Size> previewSizeList = parameters.getSupportedPreviewSizes();
                //从列表中选取接近屏幕的分辨率
                Camera.Size presize = CameraUtils.getProperSize(previewSizeList, heightPixels);
                // 设置预览大小
                parameters.setPreviewSize(presize.width, presize.height);
                //根据选出的PictureSize重新设置SurfaceView大小
                int heightPixels = this.heightPixels;
                int widthPixels = this.widthPixels;
                int size = heightPixels / presize.width < widthPixels / presize.height ? widthPixels / presize.height : heightPixels / presize.width;//取倍数小的比例
                int w = presize.height * size;
                int h = presize.width * size;
                sv_camera.setLayoutParams(new RelativeLayout.LayoutParams(w, h));
            }

        }
    }

    /**
     * 保存
     */
    public void saveBitmap() {
        String filename = photoParam.getPicPre() + DateUtil.getCurDateStr("yyyyMMddHHmmss");
        //水印内容为空白，就不画水印,默认文件名为水印
        if (photoParam.getWatermark() == null) {
            cameraBitmap = BitmapUtil.addWatermark(cameraBitmap, filename);
        } else if (!photoParam.getWatermark().trim().equals("")) {
            cameraBitmap = BitmapUtil.addWatermark(cameraBitmap, photoParam.getWatermark());
        }
        File jpgFile;
        try {
            jpgFile = BitmapUtil.Bitmap2File(cameraBitmap, photoParam.getPicQuality(), photoParam.getPicPath(), filename);
            if (jpgFile == null) {
                MessageTools.showShortToast("保存失败！请检查存储设备");
                onBackPressed();
                return;
            }
        } catch (IOException e) {
            e.printStackTrace();
            MessageTools.showShortToast( "保存失败！");
            onBackPressed();
            return;
        }
        picPaths.add(jpgFile.getAbsolutePath());
        picAdapter.notifyDataSetChanged();
        gy_pic.setSelection(picPaths.size());
    }


    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.titlebar_left_text) {
            onBackPressed();
        }

        if (v.getId() == R.id.titlebar_title_text) {
            if (((TextView) v).getText().toString().equals(getResources().getString(R.string.turn_on_lights))) {
                ((TextView) v).setText(getResources().getString(R.string.turn_off_lights));
                CameraUtils.openF(camera);
            } else {
                ((TextView) v).setText(getResources().getString(R.string.turn_on_lights));
                CameraUtils.stopF(camera);
            }
        }
        if (v.getId() == R.id.titlebar_right_pic) {
            switchCamera();
        }

        if (v.getId() == R.id.iv_shutter) {
            // 拍照
            if (camera != null) {
                camera.takePicture(null, null, pictureCallback);
                findViewById(R.id.iv_shutter).setVisibility(View.INVISIBLE);
            }
        }

        if (v.getId() == R.id.iv_save) {
            saveBitmap();
            if (picPaths.size() < photoParam.getMaxMember()) {//已拍数量未达到最大
                rl_takephoto.setVisibility(View.VISIBLE);
                rl_prephoto.setVisibility(View.GONE);
                camera.startPreview(); // 拍完照后，重新开始预览
            } else {
                onBackPressed();
            }
            findViewById(R.id.iv_shutter).setVisibility(View.VISIBLE);
        }
        if (v.getId() == R.id.iv_cancel) {
            rl_takephoto.setVisibility(View.VISIBLE);
            rl_prephoto.setVisibility(View.GONE);
            camera.startPreview(); // 拍完照后，重新开始预览
            findViewById(R.id.iv_shutter).setVisibility(View.VISIBLE);
        }

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        try {
            camera.autoFocus(new Camera.AutoFocusCallback() {
                @Override
                public void onAutoFocus(boolean b, Camera camera) {

                }
            });
        } catch (Exception e) {

        }
        return super.onTouchEvent(event);
    }

    @Override
    public void onBackPressed() {
        Intent intent = getIntent();
        Bundle bundle = new Bundle();
        bundle.putStringArrayList("results", picPaths);
        intent.putExtras(bundle);
        setResult(RESULT_OK, intent);
        myOrientation.disable();
        super.onBackPressed();
    }

    private SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {
        @Override
        public void surfaceCreated(SurfaceHolder surfaceHolder) {
            myOrientation = new MyOrientationEventListener(CameraActivity.this);//开始设置方向监听
            List<View> views = new ArrayList<>();
            views.add(iv_shutter);
            views.add(iv_switch);
            views.add(tv_back);
            views.add(tv_light);
            myOrientation.setViewsRotation(views);
            camera_direction = Camera.CameraInfo.CAMERA_FACING_FRONT;//第一次进来 设置前置 转换之后就是后置了
            switchCamera();
        }

        @Override
        public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
            try {
                setCameraAndDisplay();
            } catch (Exception e) {
                e.printStackTrace();
                MessageTools.showLongToast( "打开相机失败！请检查相机设备或相机权限");
                onBackPressed();
                return;
            }
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
            try {
                cameraDestory();
            } catch (Exception e) {
                e.printStackTrace();
                MessageTools.showLongToast("打开相机失败！请检查相机设备或相机权限");
                onBackPressed();
                return;
            }
        }
    };

    private void cameraDestory() {
        if (camera != null) {
            camera.setPreviewCallback(null);
            camera.stopPreview();
            camera.release(); // 释放照相机
            camera = null;
        }
    }

    private Camera.PictureCallback pictureCallback = new Camera.PictureCallback() {
        @Override
        public void onPictureTaken(byte[] bytes, Camera camera) {
            try {
                rl_prephoto.setVisibility(View.VISIBLE);
                rl_takephoto.setVisibility(View.GONE);
                cameraBitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                // 根据拍摄的方向旋转图像（纵向拍摄时要需要将图像旋转90度)
                Matrix matrix = new Matrix();
                if (camera_direction == Camera.CameraInfo.CAMERA_FACING_BACK) {
                    matrix.setRotate((myOrientation.getCurrentOrientation() + 1) * 90);
                }
                if (camera_direction == Camera.CameraInfo.CAMERA_FACING_FRONT) {//前置摄像头为镜面显示，如果显示为原生就要相反
                    matrix.setRotate(-(myOrientation.getCurrentOrientation() + 1) * 90);
                }
                cameraBitmap = Bitmap.createBitmap(cameraBitmap, 0, 0, cameraBitmap.getWidth(), cameraBitmap.getHeight(), matrix, true);
                iv_preview.setImageBitmap(cameraBitmap);
            } catch (Exception e) {
                e.printStackTrace();
                MessageTools.showLongToast("预览照片失败！请检查相机设备或相机权限");
                onBackPressed();
                return;
            }
        }
    };

    private CommonAdapter<String> picAdapter = new CommonAdapter<String>(this, R.layout.list_pic_item, picPaths) {
        @Override
        protected void convert(ViewHolder viewHolder, String item, int position) {
            viewHolder.setImageURL(R.id.iv_pic, "file://" + item, new DisplayImageOptions.Builder().build());
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            View view = super.getView(position, convertView, parent);
            view.findViewById(R.id.iv_delete).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    File file = new File(picPaths.get(position));
                    if (file.exists()) {
                        file.delete();
                    }
                    picPaths.remove(position);
                    picAdapter.notifyDataSetChanged();
                }
            });
            return view;
        }
    };
}

